package com.bootdo.clouddo.controller.book;

import com.bootdo.clouddo.controller.common.CommonController;
import com.bootdo.clouddo.domain.book.BookBookmark;
import com.bootdo.clouddo.service.book.IBookBookmarkService;
import com.bootdo.clouddo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@RestController
@RequestMapping("/book/v1/bookmark")
public class BookmarkController extends CommonController {

    @Autowired
    private IBookBookmarkService biz;

    @PutMapping("/{bookId}/{siteId}/{url}")
    public R add(@PathVariable Long bookId, @PathVariable Integer siteId, @PathVariable String url, String title){
        try{
            BookBookmark record = buildRecord(bookId, siteId, url, title, getUid());
            return R.data(biz.add(record));
        }catch (DuplicateKeyException e1) {
            return R.data(0);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @DeleteMapping("/{bookId}/{siteId}/{url}")
    public R del(@PathVariable Long bookId, @PathVariable Integer siteId, @PathVariable String url){
        try{
            return R.data(biz.delete(bookId, siteId, url, getUid()));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @GetMapping("/find/{bookId}/{siteId}")
    public R find(@PathVariable Long bookId, @PathVariable Integer siteId, Integer page){
        try{
            //PageHelper.startPage(page, 15);
            return R.data(biz.findByUid(bookId, siteId, getUid()));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    private BookBookmark buildRecord(Long bookId, Integer siteId, String url, String title, Long uid){
        BookBookmark record = new BookBookmark();
        record.setAddTime(new Date());
        record.setBookId(bookId);
        record.setSiteId(siteId);
        record.setUid(uid);
        record.setUrl(url);
        record.setTitle(title);
        return record;
    }

}
